<template>
	<div
		ref="rootRef"
		:tabindex="disabled?-1:0"
		:class="classes()"
		:style="{
			fontSize:toCssLength(size),
			color,
		}"
		@click="clickFn"
	>
		<slot
			name="icon"
			v-bind="slotScope()"
		>
			<svg
				focusable="false"
				viewBox="0 0 24 24"
				aria-hidden="true"
				class="pf-Radio_icon"
			>
				<path
					d="M12,22a10,10 0 0 1 -10,-10a10,10 0 0 1 10,-10a10,10 0 0 1 10,10a10,10 0 0 1 -10,10m0,-22a12,12 0 0 0 -12,12a12,12 0 0 0 12,12a12,12 0 0 0 12,-12a12,12 0 0 0 -12,-12"
				/>
				<path
					class="pf-Radio_dot"
					d="M12,6a6,6 0 0 0 -6,6a6,6 0 0 0 6,6a6,6 0 0 0 6,-6a6,6 0 0 0 -6,-6"
				/>
			</svg>
		</slot>
		<div
			v-if="label||$slots.default"
			class="pf-Radio_label"
		><slot v-bind="slotScope()">{{label}}</slot></div>
	</div>
</template>

<script setup lang="ts">
import type {
	BeforeProcessor,
} from '../../../type';
import {shallowRef} from 'vue';
import {toCssLength} from '../../../util';
/**
 * 单选框组件
 * @author 唐国雄
 * @date 2022/11/14
 * 属性----------------------
 * v-model			当前值
 * :active			手动控制是否选中
 * :before-active	选中前置处理器
 * :name			唯一键
 * :label			标签名
 * :color			颜色
 * :size			大小
 * :disabled		禁用状态
 * 事件----------------------
 * @update:modelValue	值变化
 * 插槽----------------------
 * #default			自定义标签
 * #icon			自定义图案
 */
const emit=defineEmits<{
	(e:'update:modelValue',val:any):void;
}>();
const props=withDefaults(defineProps<{
	modelValue?:any;
	active?:boolean|null;
	beforeActive?:BeforeProcessor<any>;
	name?:any;
	label?:string;
	color?:string;
	size?:string|number;
	disabled?:boolean;
}>(),{
	active:null,
});
const rootRef=shallowRef<HTMLElement>(null);
//region 选中状态
const activeStatus=():boolean => {
	const {active}=props;
	return active==null
		?props.modelValue===(props.name??props.label)
		:active;
};
//endregion
//region 类名
const classes=() => {
	return 'pf-Radio'+
		(activeStatus()?'':' pf--inactive')+
		(props.disabled?' pf--disabled':'');
};
//endregion
//region 插槽作用域
const slotScope=() => {
	return {
		active:activeStatus(),
		disabled:props.disabled,
	};
};
//endregion
//region 点击事件
function clickFn(){
	if(activeStatus()||props.disabled) return;
	const val=props.name??props.label;
	rootRef.value.blur();
	Promise.resolve(props.beforeActive?.(val)).then((success) => {
		if(success===false){
			throw 'beforeActive阻止';
		}
		emit('update:modelValue',val);
	}).catch(function(){});
}
//endregion
</script>

<script lang="ts">
export default {};
</script>